package com.tsq.push.provider.builder;

import cn.hutool.core.collection.CollectionUtil;
import com.aliyuncs.push.model.v20160801.MassPushRequest;
import com.tsq.push.api.dto.PushDTO;
import com.tsq.push.api.dto.base.PushDevice;
import com.tsq.push.api.dto.base.PushText;
import io.micrometer.core.instrument.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建批量推送
 *
 * @author Tango
 * @since 2020/8/11
 */
public class MassPushBuilder implements PushBuilder {

    private MassPushRequest request;

    private List<PushDevice> pushDeviceList;
    private PushText pushText;


    MassPushBuilder() {
        request = new MassPushRequest();
        pushDeviceList = new ArrayList<>();
    }

    //应用key
    public MassPushBuilder key(String appKey) {
        request.setAppKey(Long.valueOf(appKey));
        return this;
    }

    //目标
    public MassPushBuilder device(String target, String targetValue) {
        pushDeviceList.add(new PushDevice(target, targetValue));
        return this;
    }

    //消息内容
    public MassPushBuilder info(String pushType, String title, String body) {
        pushText = new PushText(pushType, title, body);
        return this;
    }

    /**
     * 从DTO创建
     * @param pushDTO
     * @return
     */
    public MassPushRequest buildWithDTO(PushDTO pushDTO) {
        request.setActionName("MassPush");
        if (StringUtils.isNotBlank(pushDTO.getAppKey())) {
            request.setAppKey(Long.valueOf(pushDTO.getAppKey()));
        }
        if (CollectionUtil.isEmpty(pushDTO.getPushTaskList())) {
            List<MassPushRequest.PushTask> pushTaskList = new ArrayList<>();
            List<PushDevice> pushDeviceList = pushDTO.getPushDeviceList();
            PushText pushText = pushDTO.getPushText();
            for (PushDevice device : pushDeviceList) {
                MassPushRequest.PushTask pushTask = new MassPushRequest.PushTask();
                pushTask.setDeviceType("ALL");
                pushTask.setAndroidNotifyType("BOTH");
                pushTask.setAndroidNotificationChannel("1");
                pushTask.setStoreOffline(true);

                pushTask.setDeviceType(device.getDeviceType());
                pushTask.setTarget(device.getTarget());
                pushTask.setTargetValue(device.getTargetValue());
                pushTask.setPushType(pushText.getPushType());
                pushTask.setTitle(pushText.getTitle());
                pushTask.setBody(pushText.getBody());
                pushTaskList.add(pushTask);
            }
            request.setPushTasks(pushTaskList);
        } else {
            request.setPushTasks(pushDTO.getPushTaskList());
        }
        return request;
    }

    public MassPushRequest build() {
        PushDTO pushDTO = new PushDTO();
        pushDTO.setPushText(pushText);
        pushDTO.setPushDeviceList(pushDeviceList);
        return buildWithDTO(pushDTO);
    }

}
